package linkedlist.leetcode_234;

/**
 * 判断回文链表
 */
public class BestSoluition {
    public boolean isPalindrome(ListNode head) {
        //边界处理
        if(head == null || head.next == null){
            return true;
        }
        ListNode fast = head;
        ListNode slow = head;
        //循环结束时，slow指向中间节点
        while(fast.next != null && fast.next.next != null){
            fast = fast.next.next;
            slow = slow.next;
        }
        ListNode next = slow.next;
        slow.next = null;

        //反转后半部分链表
        ListNode t = reverse(next);
        while(head != null && t != null){
            if(head.val != t.val){
                return false;
            }
            head = head.next;
            t = t.next;
        }
        return true;
    }
    public ListNode reverse(ListNode head){
        ListNode pre = null;
        while(head != null){
            ListNode next = head.next;
            head.next = pre;
            pre = head;
            head = next;
        }
        return pre;
    }
}
